<script lang="tsx">
/**
 * 图片表单组件
 */
export default {
  name: "yy-image-form"
}
</script>

<script lang="tsx" setup>
import {computed, ref, watch} from "vue"
import {ElImage} from 'element-plus'
import {globalSetting} from "../../../config/global-setting.ts"
import {YyImageFormCustomerEvents, YyImageFormCustomerProps} from "./index.ts"

/**
 * 定义emit
 */
const emit: any = defineEmits<YyImageFormCustomerEvents>()

/**
 * 定义props
 */
interface YyImageFormProps {
  modelValue: string,
  props?: YyImageFormCustomerProps
}

const props = withDefaults(defineProps<YyImageFormProps>(), {
  props: () => ({
    lazy: true,
    fit: 'cover',
    width: 200,
    height: 200,
    isRem: false,
    previewTrigger: 'click'
  })
})

/**
 * 图片实例
 */
const imageRef = ref<any>()

/**
 * 图片数据
 */
const imageData = ref()

/**
 * 计算样式
 */
const style = computed(() => {
  if (props.props.isRem) {
    return {
      width: props.props.width + "rem",
      height: props.props.height + "rem"
    }
  } else {
    return {
      width: props.props.width + "px",
      height: props.props.height + "px"
    }
  }
})

/**
 * 预览
 */
const handleClick = () => {
  if (props.props.previewTrigger === 'click' && imageRef.value) {
    imageRef.value.showPreview()
  }
  emit("click")
}

/**
 * 处理悬停预览
 */
const handleMouseEnter = () => {
  if (props.props.previewTrigger === 'hover' && imageRef.value) {
    imageRef.value.showPreview()
  }
}

/**
 * 图片加载成功
 */
const handleLoad = () => {
  emit("load")
}

/**
 * 图片加载失败
 */
const handleError = () => {
  emit("error")
}

/**
 * 监听
 */
watch(() => props.modelValue, (newValue: any) => {
  if (newValue) {
    imageData.value = "/Uploads" + newValue
  }
}, {
  deep: true,
  immediate: true
})

// 监听props变化以确保响应式更新
watch(
    () => props.props,
    () => {
      // 触发重新计算
    },
    {deep: true}
)
</script>

<template>
  <el-image
      ref="imageRef"
      :fit="props.props.fit"
      :lazy="props.props.lazy"
      :src="globalSetting.uploadUrl + imageData"
      :style="style"
      v-bind="$attrs"
      @click="handleClick"
      @error="handleError"
      @load="handleLoad"
      @mouseenter="handleMouseEnter"
  />
</template>

<style lang="scss" scoped>

</style>